<?php
error_reporting(E_ALL ^ E_NOTICE^ E_WARNING);
ini_set('display_errors', '0'); 
date_default_timezone_set('Asia/Shanghai');

class JddjCommon
{
    private $connectUrl;
    private $appkey;
    private $appsecret;
    private $token;
    private $apiVersion = "2.0";

    protected $connectTimeout   = 3000;
    protected $readTimeout  = 60000;

	public function __construct()
    {
        $this->connectUrl = 'https://openo2o.jd.com/mockapi/';
        $this->appkey = '92f226be12c9428eb91f2de6184d448b';
        $this->appsecret = '9ca75d06246b44ea81f373b9fd19c969';
        $this->token = '06e874ca-fee2-4e9d-aa67-3ce78d76e983'; //杭州
    }

    // 京东参数
    // $cids = array(
    //     1 => array(
    //         // 北京
    //         'stationNo' => '11648912',
    //         'key' => 'c91e6e27be1243b7942addc7315dcac7',
    //         'secret' => 'e6b150d082dc497dbc662ebe09eec522',
    //         'token' => '3dac5617-73d4-4c4c-be77-b8327b4778d0',
    //         ),
    //     2 => array(
    //         // 深圳
    //         'stationNo' => '11648912',
    //         'key' => '961fd5cb3311487699f1cfe7b3fd79a0',
    //         'secret' => '7daada4fe79140449755f0f11bb522bd',
    //         'token' => 'b7836a2e-3745-4fe6-8860-d8d7f98ef683',
    //         ),
    //     3 => array(
    //         // 广州
    //         ),
    //     4 => array(
    //         // 上海
    //         'stationNo' => '11648912',
    //         'key' => '176d329eeea348069148d06fa6864781',
    //         'secret' => '268cf663d2e84560bc3e7be5402ea284',
    //         'token' => '765590c0-d48e-4609-b04a-738adc4665f6',
    //         ),
    //     5 => array(
    //         // 杭州
    //         'stationNo' => '11648912',
    //         'key' => '92f226be12c9428eb91f2de6184d448b',
    //         'secret' => '9ca75d06246b44ea81f373b9fd19c969',
    //         'token' => '06e874ca-fee2-4e9d-aa67-3ce78d76e983',
    //         ),
    //     6 => array(
    //         // 天津
    //         'stationNo' => '11648912',
    //         'key' => '6e354663648249b19fddd157f5b0589c',
    //         'secret' => '3e8c992e7e164a159d52a89ed3fc0915',
    //         'token' => '1078c145-edca-43bc-b170-ba478e759cfa',
    //         ),
    // );

    protected function generateSign($params)
    {
        $stringToBeSigned = $this->paramsToString($params);
        return strtoupper(md5($stringToBeSigned));
    }

    protected function verifySign($params)
    {
        $stringToBeSigned = $this->paramsToString($params);

        $sign = $params["sign"];
        if(!empty($sign)){
            return $sign == strtoupper(md5($stringToBeSigned));
        }
        return false;
    }

    protected function paramsToString($params)
    {
        ksort($params);

        $sortedString = $this->appsecret;
        foreach ($params as $k => $v)
        {
            $v = (string)$v;
            if("sign" !== $k /*&& strlen($v) > 0*/)
            {
                $sortedString .= "$k$v";
            }
        }

        $sortedString .= $this->appsecret;

        return $sortedString;
    }
    
    /*
        获取公共参数
        params
            params 传输的参数
    */
    public function getPostData($params = array())
    {
        $apiParams = array();
        //应用级参数
        $apiParams['jd_param_json'] = json_encode($params);
        //系统级别参数
        $apiParams['token']       = $this ->token;
        $apiParams['app_key']     = $this ->appkey;
        $apiParams['timestamp']   = date('Y-m-d H:i:s');
        $apiParams['v']           = $this ->apiVersion;
        $apiParams['format']      = 'json';
        $apiParams["sign"]        = $this->generateSign($apiParams);

        return $apiParams;
    }

    public function sendData($url, $postFields = null)
    {
        $url = $this->connectUrl.$url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($this->readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if ($this->connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }

        if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        if (is_array($postFields) && 0 < count($postFields))
        {
            $header = array("content-type: application/x-www-form-urlencoded; charset=UTF-8");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields, '', '&'));
        }
        $reponse = curl_exec($ch);

        // var_dump(curl_errno($ch), curl_error($ch), curl_getinfo($ch), $url, $return_str);die;
        $reponse = json_decode($reponse, true);
        if (curl_errno($ch))
        {
            throw new Exception(curl_error($ch), 0);
        }
        else
        {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode)
            {
                throw new Exception($reponse, $httpStatusCode);
            }
        }
        curl_close($ch);
        return $reponse;
    }
    /**
    *   写日志
    */
    public function DLOG($log_content='', $log_level='', $log_name='')
    { 

        if(empty($log_level)||empty($log_content))
            return;
        
        
        if(empty($log_name) && $log_level == 'run')
            $log_name = 'run';

        $log_dir = "/mnt/logs/";
        $log_file = $log_dir.$log_name.".".date('Y-m-d').".log";
        
        //默认每行日志必写的内容，统一在这里处理
        // ZHANGXI 2015/1/7 for regular
        $time = sprintf("%8s.%03d",date('H:i:s'),floor(microtime()*1000));
        //$time = date('H:i:s').".".floor(microtime()*1000);
        $ip = sprintf("%15s",$_SERVER["REMOTE_ADDR"]);

        $id =   "req-Fn";

        $path_arr = explode("/", $_SERVER['REQUEST_URI']);

        $content_prefix = "[ ".$time." ".$ip." ".$id." ".$log_level." ".$path_arr[1]." ".$path_arr[2]." ] ";

        error_log($content_prefix.$log_content." [".getmypid()."]\n", 3, $log_file);
        return true;
    }
}